package lpg.tool.optionpg;

import java.util.Map;
import java.util.TreeMap;

class PathSet
{
    PathSet()
    {
    }

    void merge(PathSet pathSet)
    {
        for (Map.Entry<Character, PathElement> entry : pathSet.elemMap.entrySet())
        {
            char c = entry.getKey();
            PathElement pathSetElement = entry.getValue();
            PathElement element = elemMap.get(c);
            if (element == null)
            {
                elemMap.put(c, pathSetElement);
            }
            else
            {
                // Keep order
                if (element.path.compareTo(pathSetElement.path) <= 0)
                {
                    element.merge(pathSetElement);
                }
                else
                {
                    pathSetElement.merge(element);
                    elemMap.put(c, pathSetElement);
                }
            }
        }
    }

    String getSingleElementPath()
    {
        if (elemMap.size() == 1)
        {
            return elemMap.values().iterator().next().path;
        }
        return null;
    }

    public String toString()
    {
        return toString("", 0);
    }

    String toString(String indent, int prefixLength)
    {
        StringBuilder buf = new StringBuilder();
        for (PathElement element : elemMap.values())
        {
            buf.append(element.toString(indent, prefixLength));
        }
        return new String(buf);
    }

    final Map<Character, PathElement> elemMap = new TreeMap<Character, PathElement>();

}
